from window_ui import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication,QTableWidgetItem,QHeaderView,QPushButton,QWidget,QAbstractItemView
# from PyQt5.QtCore import pyqtSignal,QObject,QSize,Qt,QStringListModel,QTextStream
from PyQt5.QtGui import QIcon,QFont,QColor
import sys,json
from common import signalHandle
from TQ  import TQapi
from threading import Thread
from Model_Control import TableData
guiDestroyFlag=False
class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self,signalHandle,tqApi) -> None:
        super().__init__()   #QMainWindow的初始化
        self.setupUi(self)   #把Qmainwindow放进UI类，作为背景窗口，然后添加控件
        self.tableData=TableData(self.tableWidget,tqApi)
        signalHandle.warnMsgSignal.connect(self.warnMsgSignal)
        with open('./setting.json','r')as f:
            setting=json.load(f)
        
        for index,width in enumerate(setting['table_1_colWidth']):
            self.tableWidget.setColumnWidth(index,width)
        for index,width in enumerate(setting['table_2_colWidth']):
            self.tableWidget_2.setColumnWidth(index,width)
    def warnMsgSignal(self,dc):
        self.activateWindow()
        self.tableWidget_2.insertRow(0)
        index=0
        for colName in ('ID','timeStr','warnMsg'):
            newItem=QTableWidgetItem(str(dc[colName]))
            
            self.tableWidget_2.setItem(0,index,newItem)
            index+=1

    def closeEvent(self, event):
        print('guiDestroyFlag')
        global guiDestroyFlag
        guiDestroyFlag=True

        setting={
            "table_1_colWidth":[],
            "table_2_colWidth":[]
        }
        for index in range(self.tableWidget.columnCount()):
            setting["table_1_colWidth"].append(self.tableWidget.columnWidth(index))
        for index in range(self.tableWidget_2.columnCount()):
            setting["table_2_colWidth"].append(self.tableWidget_2.columnWidth(index))
        with open('./setting.json','w')as f:
            json.dump(setting,f)
def TQapiThread(tqApi,signalHandle):
    while 1:
        tqApi.api.wait_update()
        signalHandle.TQwaitUpdateSig.emit()
        if guiDestroyFlag:break
    print('tqApi.api.close')
    tqApi.api.close()
if __name__=="__main__":
    app = QApplication(sys.argv)
    tqApi=TQapi(signalHandle)
    Thread(target=TQapiThread,args=(tqApi,signalHandle)).start()
    mWindow=MainWindow(signalHandle,tqApi)
    mWindow.show()
    font = QFont("Arial", 14)
    app.setFont(font)
    sys.exit(app.exec())